//
// Created by tacom on 2024/9/25.
//

#include "iostream"
#include "libusb.h"

#define VID  0xF055
#define PID  0x9999
#define EP_OUT 0x01
#define EP_IN 0x82

int main(){
    libusb_device_handle *deviceHandle = NULL;
    libusb_context *ctx = NULL;

    int ret;
    ret = libusb_init(&ctx);
    if(ret < 0){
        std::cout << "Init libusb Error" << std::endl;
        return -1;
    }

    deviceHandle = libusb_open_device_with_vid_pid(ctx, VID, PID);
    if(deviceHandle == NULL){
        std::cout << "Device Open Error" << std::endl;
        libusb_exit(ctx);
        return -1;
    }

    if(libusb_kernel_driver_active(deviceHandle, 0) == 1){
        ret = libusb_detach_kernel_driver(deviceHandle, 0);
        if(ret < 0){
            std::cout << "Unable detach from kernel" << std::endl;
            libusb_close(deviceHandle);
            libusb_exit(ctx);
            return -1;
        }
    }

    ret = libusb_claim_interface(deviceHandle, 0);
    if(ret < 0){
        std::cout << "Unable Register Signal to OS" << std::endl;
        libusb_close(deviceHandle);
        libusb_exit(ctx);
        return -1;
    }

    unsigned char writeBuf[64] = "Hello, Cpp Device";
    unsigned char readBuf[64] = {0};
    int actualLength;

    ret = libusb_bulk_transfer(deviceHandle, EP_OUT, writeBuf, sizeof (writeBuf),
                               &actualLength, 0);

    if(ret < 0){
        std::cout << "Unable Send data to device" << std::endl;
        libusb_close(deviceHandle);
        libusb_exit(ctx);
        return -1;
    }

    ret = libusb_bulk_transfer(deviceHandle, EP_IN, readBuf, sizeof (readBuf),
                               &actualLength, 0);

    if(ret < 0){
        std::cout << "Unable Read data to device" << std::endl;
        libusb_close(deviceHandle);
        libusb_exit(ctx);
        return -1;
    }

    std::cout << readBuf << std::endl;
    libusb_close(deviceHandle);
    libusb_exit(ctx);
    return 0;

}